"""
Author : ZhengShiQi
DateTime: 2025/9/11 13:55
FileName: mocks.py
description: 管理模拟服务的端点
"""
from fastapi import APIRouter, Depends, HTTPException, Request, status
from sqlalchemy.orm import Session
from app.models.schemas import MockApi, MockApiCreate, HttpMethod
from app.services.mock_service import get_mock_configs, create_mock_config, update_mock_config, delete_mock_config, create_mock_api_with_wiremock
from app.services.db_service import get_all_mock_apis, create_mock_api, get_mock_api_by_id, update_mock_api, delete_mock_api
from app.models.database import get_db, MockApiConfig
from fastapi import Response
from typing import Dict, Any, List
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

router = APIRouter(prefix="/v1", tags=["模拟配置"])
"""
编辑接口请求
"""
@router.put("/mocs/{id}", response_model=Dict[str, Any])
def update_mock_config_endpoint(id: int, mock: MockApiCreate, request: Request, db: Session = Depends(get_db)):
    try:
        # 直接使用传入的mock对象，与新增接口保持一致
        db_mock = update_mock_config(db=db, id=id, mock_api=mock)
        if db_mock is None:
            raise HTTPException(status_code=404, detail="Mock config not found")
        # 返回成功响应
        return {
            "success": True,
            "code": 200,
            "msg": "编辑接口成功"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新Mock规则失败: {str(e)}")
"""
查询列表接口请求
"""
@router.get("/mocs", response_model=Dict[str, Any])
def read_mock_configs(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    try:
        db_mocks = get_all_mock_apis(db, skip=skip, limit=limit)
        # 转换为字典列表并格式化时间
        mock_list = []
        for mock in db_mocks:
            mock_dict = {
                "id": mock.id,
                "name": mock.name,
                "url": mock.url,
                "method": mock.method,
                "headers": mock.headers,
                "body": mock.body,
                "status_code": mock.status_code,
                "created_at": mock.created_at.isoformat() + "Z" if mock.created_at else None,
            }
            mock_list.append(mock_dict)
        
        return {
            "code": 200,
            "success": True,
            "msg": "查询接口列表成功",
            "data": mock_list
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"查询接口列表失败: {str(e)}")

"""
新增接口请求
"""
@router.post("/mocs", response_model=Dict[str, Any])
def create_mock_rule(mock: MockApiCreate, db: Session = Depends(get_db)):
    try:
        # 创建Mock规则
        logger.info(f"这是前置条件{mock}")
        db_mock = create_mock_api_with_wiremock(db=db, mock_api=mock)

        # 返回成功响应
        return {
            "success": True,
            "code": 200,
            "msg": "新增接口成功"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建Mock规则失败: {str(e)}")
"""
查询接口请求
"""
@router.get("/mocs/{pk}", response_model=Dict[str, Any])
def read_mock_config_detail(pk: int, db: Session = Depends(get_db)):
    try:
        logger.info(f"开始查询ID为 {pk} 的Mock API详情")
        # 根据ID获取Mock API详情
        db_mock = get_mock_api_by_id(db, pk)
        if db_mock is None:
            logger.warning(f"未找到ID为 {pk} 的Mock API")
            raise HTTPException(status_code=404, detail="Mock config not found")
        
        logger.info(f"成功获取到Mock API: {db_mock.name}")
        
        # 转换为字典并格式化时间
        mock_dict = {
            "id": db_mock.id,
            "name": db_mock.name,
            "url": db_mock.url,
            "method": db_mock.method,
            "headers": db_mock.headers,
            "body": db_mock.body,
            "status_code": db_mock.status_code,
            "created_at": db_mock.created_at.isoformat() + "Z" if db_mock.created_at else None,
            "updated_at": db_mock.updated_at.isoformat() + "Z" if db_mock.updated_at else None
        }
        
        logger.info(f"格式化后的数据: {mock_dict}")
        
        # 返回成功响应
        return {
            "code": 200,
            "success": True,
            "msg": "查询接口详情成功",
            "data": mock_dict
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"查询接口详情失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"查询接口详情失败: {str(e)}")

"""
删除接口请求
"""
@router.delete("/mocs/{pk}", response_model=Dict[str, Any])
def delete_mock_config_endpoint(pk: int, db: Session = Depends(get_db)):
    try:
        # 删除Mock配置
        db_mock = delete_mock_config(db=db, mock_id=pk)
        if db_mock is None:
            raise HTTPException(status_code=404, detail="Mock config not found")
        # 返回成功响应
        return {
            "code": 200,
            "success": True,
            "msg": "删除接口成功"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除Mock规则失败: {str(e)}")